package com.elcom.player;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.net.TrafficStats;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageButton;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.elcom.player.overlay.overlay;

public class VideoPlayerActivity extends Activity implements
			OnCompletionListener, OnErrorListener, OnInfoListener,
			OnBufferingUpdateListener, OnPreparedListener, OnSeekCompleteListener,
			OnVideoSizeChangedListener, SurfaceHolder.Callback,
			MediaController.MediaPlayerControl{

	private static final int SETTING_REQ    = 0x10;	
	private static SharedPreferences settings;
	private String subtemp = "/subtemp.srt";
	MediaController controller;
	Display currentDisplay;
	SurfaceView surfaceView;
	SurfaceHolder surfaceHolder;
	MediaPlayer mediaPlayer;
	String mPath, mTitle;
	
	View mainView;
	TextView mcCurrentTime;
	TextView mcTotalTime;
	TextView mcFileName;
	ImageButton mcPlay;
	SeekBar mcSeek;
	RelativeLayout mcLayout;
	
	private ImageButton mSize;
	private ImageButton mSubSetting;
	private TextView mInfo;
    private static final int SURFACE_BEST_FIT = 0;
    private static final int SURFACE_FIT_HORIZONTAL = 1;
    private static final int SURFACE_FIT_VERTICAL = 2;
    private static final int SURFACE_FILL = 3;
    private static final int SURFACE_16_9 = 4;
    private static final int SURFACE_4_3 = 5;
    private static final int SURFACE_ORIGINAL = 6;
    private int mCurrentSize = SURFACE_BEST_FIT;
    private overlay mOverPlay;
    
    // size of the video
    private int mVideoHeight;
    private int mVideoWidth;
    private int mSarNum;
    private int mSarDen;
    
	TextView mTextSubtitle;
	private Subtitle mSubtitle;
	
	int videoWidth = 0;
	int videoHeight = 0;
	int totalDuration;
	int playedDuration;
	private static boolean paused;
	private boolean bSeeking;
	boolean readyToPlay = false;
	public final static String LOGTAG = "STREAMING_VIDEO_PLAYER";
	private Updater seekBarUpdater = new Updater();
	private Handler mHandler = new Handler();
	
	private int postionBeforeSetting=0;
	
	private void log(String ss){
		Log.d("EVPLayer", ss);
	}
	private void toast(String ss){
		Toast.makeText(VideoPlayerActivity.this, ss, Toast.LENGTH_SHORT).show();
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//gui start
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().addFlags(LayoutParams.FLAG_FULLSCREEN);
		//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		//gui end
		setContentView(R.layout.videoview);
		readSettings();
		Intent intent = getIntent();
		mPath = intent.getStringExtra("videofilename");
		Globals.setFileName(mPath);
		mTitle = Globals.fileTitle;
		//toast(mPath);
		paused = false;
		if (TextUtils.isEmpty(mPath))
			mPath = Environment.getExternalStorageDirectory() + "test.mp4";
		else if (intent.getData() != null)
			mPath = intent.getData().toString();
		
		mainView = this.findViewById(R.id.MainView);
		mcCurrentTime = (TextView)findViewById(R.id.mediacontroller_time_current);
		mcTotalTime = (TextView)findViewById(R.id.mediacontroller_time_total);
		mcFileName = (TextView)findViewById(R.id.mediacontroller_file_name);
		mcSeek = (SeekBar)findViewById(R.id.mediacontroller_seekbar);
		mSize = (ImageButton) findViewById(R.id.mediacontroller_size);
		mInfo = (TextView) findViewById(R.id.player_overlay_info);
		mcLayout = (RelativeLayout)findViewById(R.id.mediacontroller_layout);
		mcPlay = (ImageButton)findViewById(R.id.mediacontroller_play_pause);
		mSubSetting = (ImageButton)findViewById(R.id.mediacontroller_subtitle);
		mTextSubtitle = (TextView)findViewById(R.id.subtitle);
		
		
		 mOverPlay = new overlay(mInfo, getBaseContext(), VideoPlayerActivity.this);
		//mOverPlay.showInfo("nguyen", 5000);
		mcSeek.setOnSeekBarChangeListener(mcSeekChangeListener);
		mSize.setOnClickListener(mSizeListener);
		mSubSetting.setOnClickListener(mSubSettingListener);
		
		mainView.setOnClickListener(mMainViewListener);
		mcPlay.setOnClickListener(mcPlayListener);
		surfaceView = (SurfaceView) this.findViewById(R.id.SurfaceView);
		surfaceHolder = surfaceView.getHolder();
		surfaceHolder.addCallback(this);
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		

		mSarNum = 1;
		mSarDen = 1;
		
		mediaPlayer = new MediaPlayer();
		mediaPlayer.setOnCompletionListener(this);
		mediaPlayer.setOnErrorListener(this);
		mediaPlayer.setOnInfoListener(this);
		mediaPlayer.setOnPreparedListener(this);
		mediaPlayer.setOnSeekCompleteListener(this);
		mediaPlayer.setOnVideoSizeChangedListener(this);
		mediaPlayer.setOnBufferingUpdateListener(this);
		try {
			mediaPlayer.setDataSource(mPath);
			//load sub
			mSubtitle = new Subtitle("/mnt/sdcard/" + Globals.fileTitle + ".srt",mTextSubtitle);
			if(mSubtitle.isParseSubtitle()){
				mOverPlay.showInfo("Loaded Subtitle: " +Globals.fileTitle + ".srt", 3000);
			}
		} catch (IllegalArgumentException e) {
			Log.v(LOGTAG, e.getMessage());
			finish();
		} catch (IllegalStateException e) {
			Log.v(LOGTAG, e.getMessage());
			finish();
		} catch (IOException e) {
			Log.v(LOGTAG, e.getMessage());
			finish();
		}
		currentDisplay = getWindowManager().getDefaultDisplay();
		
	}
	private final OnClickListener mSubSettingListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
        	Intent i = new Intent(VideoPlayerActivity.this, Setting.class);
			i.putExtra("SUBTITLE", Globals.dbSubtitle);
			i.putExtra("SUBTITLESIZE", Globals.dbSubtitleSize);
			i.putExtra("SUBTITLEFONT", Globals.dbSubtitleFont);
			i.putExtra("SUBTITLEFILE", Globals.dbSubtitleFile);
			i.putExtra("SUBTITLEPOS", Globals.dbSubtitlePos);
			i.putExtra("SUBTITLECOL", Globals.dbSubtitleCol);
			// pause video when onto etting
			postionBeforeSetting = mediaPlayer.getCurrentPosition();
			mediaPlayer.stop();
			seekBarUpdater.stopIt();	
			paused = true;
        	startActivityForResult(i, SETTING_REQ);
		}
	};
	 private final OnClickListener mSizeListener = new OnClickListener() {

	        @Override
	        public void onClick(View v) {
	            if (mCurrentSize < SURFACE_ORIGINAL) {
	                mCurrentSize++;
	            } else {
	                mCurrentSize = 0;
	            }
	            changeSurfaceSize();
	            mOverPlay.clickListener(mCurrentSize);
	        }
	};
	@Override
    public void onConfigurationChanged(Configuration newConfig) {
        setSurfaceSize(mVideoWidth, mVideoHeight, mSarNum, mSarDen);
        super.onConfigurationChanged(newConfig);
    }
	 public void setSurfaceSize(int width, int height, int sar_num, int sar_den) {
	        // store video size
	        mVideoHeight = height;
	        mVideoWidth = width;
	        mSarNum = sar_num;
	        mSarDen = sar_den;
//	        Message msg = mHandler.obtainMessage(SURFACE_SIZE);
//	        mHandler.sendMessage(msg);
	    }
	 private void changeSurfaceSize() {
	        // get screen size
	        int dw = getWindow().getDecorView().getWidth();
	        int dh = getWindow().getDecorView().getHeight();

	        // getWindow().getDecorView() doesn't always take orientation into account, we have to correct the values
	        boolean isPortrait = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
	        if (dw > dh && isPortrait || dw < dh && !isPortrait) {
	            int d = dw;
	            dw = dh;
	            dh = d;
	        }
	        if (dw * dh == 0)
	            return;

	        // compute the aspect ratio
	        double ar, vw;
	        double density = (double)mSarNum / (double)mSarDen;
	        if (density == 1.0) {
	            /* No indication about the density, assuming 1:1 */
	            vw = mVideoWidth;
	            ar = (double)mVideoWidth / (double)mVideoHeight;
	        } else {
	            /* Use the specified aspect ratio */
	            vw = mVideoWidth * density;
	            ar = vw / mVideoHeight;
	        }

	        // compute the display aspect ratio
	        double dar = (double) dw / (double) dh;

	        switch (mCurrentSize) {
	            case SURFACE_BEST_FIT:
	                if (dar < ar)
	                    dh = (int) (dw / ar);
	                else
	                    dw = (int) (dh * ar);
	                break;
	            case SURFACE_FIT_HORIZONTAL:
	                dh = (int) (dw / ar);
	                break;
	            case SURFACE_FIT_VERTICAL:
	                dw = (int) (dh * ar);
	                break;
	            case SURFACE_FILL:
	                break;
	            case SURFACE_16_9:
	                ar = 16.0 / 9.0;
	                if (dar < ar)
	                    dh = (int) (dw / ar);
	                else
	                    dw = (int) (dh * ar);
	                break;
	            case SURFACE_4_3:
	                ar = 4.0 / 3.0;
	                if (dar < ar)
	                    dh = (int) (dw / ar);
	                else
	                    dw = (int) (dh * ar);
	                break;
	            case SURFACE_ORIGINAL:
	                dh = mVideoHeight;
	                dw = (int) vw;
	                break;
	        }

	        surfaceHolder.setFixedSize(mVideoWidth, mVideoHeight);
	        android.view.ViewGroup.LayoutParams lp = surfaceView.getLayoutParams();
	        lp.width = dw;
	        lp.height = dh;
	        surfaceView.setLayoutParams(lp);
	        surfaceView.invalidate();
	    }
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		paused = false;
		
		surfaceHolder = surfaceView.getHolder();
		surfaceHolder.addCallback(this);
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		mediaPlayer = new MediaPlayer();
		mediaPlayer.setOnCompletionListener(this);
		mediaPlayer.setOnErrorListener(this);
		mediaPlayer.setOnInfoListener(this);
		mediaPlayer.setOnPreparedListener(this);
		mediaPlayer.setOnSeekCompleteListener(this);
		mediaPlayer.setOnVideoSizeChangedListener(this);
		mediaPlayer.setOnBufferingUpdateListener(this);
		try {
			mediaPlayer.setDataSource(mPath);
		} catch (IllegalArgumentException e) {
			Log.v(LOGTAG, e.getMessage());
			finish();
		} catch (IllegalStateException e) {
			Log.v(LOGTAG, e.getMessage());
			finish();
		} catch (IOException e) {
			Log.v(LOGTAG, e.getMessage());
			finish();
		}
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mediaPlayer.stop();
		seekBarUpdater.stopIt();
	}
	//menu
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated   method stub
		getMenuInflater().inflate(R.menu.menu_videoplayer, menu);
        return super.onCreateOptionsMenu(menu);
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated  method stub
		switch (item.getItemId()) {
        case R.id.menu_settings:
        	Intent i = new Intent(VideoPlayerActivity.this, Setting.class);
			i.putExtra("SUBTITLE", Globals.dbSubtitle);
			i.putExtra("SUBTITLESIZE", Globals.dbSubtitleSize);
			i.putExtra("SUBTITLEFONT", Globals.dbSubtitleFont);
			i.putExtra("SUBTITLEFILE", Globals.dbSubtitleFile);
			i.putExtra("SUBTITLEPOS", Globals.dbSubtitlePos);
			i.putExtra("SUBTITLECOL", Globals.dbSubtitleCol);
			// pause video when onto etting
			postionBeforeSetting = mediaPlayer.getCurrentPosition();
			mediaPlayer.stop();
			seekBarUpdater.stopIt();	
			paused = true;
        	startActivityForResult(i, SETTING_REQ);
        	return true;
        case R.id.menu_fullscreen:
        	return true;
		}
		return super.onOptionsItemSelected(item);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		//  TODO Auto-generate method stub
		
		super.onActivityResult(requestCode, resultCode, data);
		
		if (requestCode == SETTING_REQ && resultCode == RESULT_CANCELED) {
			//  save the infrmation   weg tfro msettings   activity
			boolean subtitle     = data.getBooleanExtra("SUBTITLE", Globals.dbSubtitle);
			int     subtitlesize = data.getIntExtra("SUBTITLESIZE", Globals.dbSubtitleSize);
			String subtitlefont = data.getStringExtra("SUBTITLEFONT");
			String subtitlefile = data.getStringExtra("SUBTITLEFILE");
			int subtitlepos = data.getIntExtra("SUBTITLEPOS",Globals.dbSubtitlePos);
		    int subtitlecol = data.getIntExtra("SUBTITLECOL",Globals.dbSubtitleCol);
    
		    writeSettings(subtitle,
						  subtitlesize,
						  subtitlefont,
						  subtitlefile,
						  subtitlepos,
						  subtitlecol);
		    
		    mSubtitle.setEnable(subtitle);
		    mSubtitle.setFont(subtitlefont);
		    mSubtitle.setColor(FileManager.getSubTitleColor());
		    mSubtitle.setSize((float)FileManager.getSubTitleSize());
		    mSubtitle.setPosition(subtitlepos);
		    
		    if(subtitle){
			    if(!subtitlefile.contains("http")){
			    	mSubtitle.LoadSubtitle(subtitlefile);
			    	if(mSubtitle.isParseSubtitle()){
						mOverPlay.showInfo("Loaded Subtitle: " + subtitlefile, 3000);
					}
			    }else{
					new DownloadTask().execute(subtitlefile);
				}
		    }else{
		    	mOverPlay.showInfo("Disable Subtitle", 3000);
		    }
		    
		    
		}
	}
	public void writeSettings(boolean subtitle,
							  int subtitlesize,
							  String subtitlefont,
							  String subtitlefile,
							  int subtitlepos,
							  int subtitlecol)
	{
		SharedPreferences.Editor editor = settings.edit();
		editor.putBoolean(Globals.PREFS_SUBTITLE, subtitle);
		editor.putInt(Globals.PREFS_SUBTITLESIZE, subtitlesize);
		editor.putString(Globals.PREFS_SUBTITLEFONT, subtitlefont);
		editor.putString(Globals.PREFS_SUBTITLEFILE, subtitlefile);
		editor.putInt(Globals.PREFS_SUBTITLEPOS, subtitlepos);
		editor.putInt(Globals.PREFS_SUBTITLECOL, subtitlecol);
		editor.commit();
		
		Globals.setShowSubTitle(subtitle);
		Globals.setSubTitleSize(subtitlesize);
		Globals.setSubTitleFont(subtitlefont);
		Globals.setSubTitleFile(subtitlefile);
		Globals.setSubTitlePos(subtitlepos);
		Globals.setSubTitleCol(subtitlecol);
	}
	public void readSettings() {

		settings = getSharedPreferences(Globals.PREFS_NAME, MODE_PRIVATE);
		Globals.dbSubtitle     = settings.getBoolean(Globals.PREFS_SUBTITLE, Globals.dbSubtitle);
		Globals.dbSubtitleSize = settings.getInt(Globals.PREFS_SUBTITLESIZE, Globals.dbSubtitleSize);
		Globals.dbSubtitleFont = settings.getString(Globals.PREFS_SUBTITLEFONT, Globals.dbSubtitleFont);
		Globals.dbSubtitleFile = settings.getString(Globals.PREFS_SUBTITLEFILE,Globals.dbSubtitleFile);
		Globals.dbSubtitlePos = settings.getInt(Globals.PREFS_SUBTITLEPOS,Globals.dbSubtitlePos);
		Globals.dbSubtitleCol = settings.getInt(Globals.PREFS_SUBTITLECOL,Globals.dbSubtitleCol);
		
		Globals.setShowSubTitle(Globals.dbSubtitle);
		Globals.setSubTitleSize(Globals.dbSubtitleSize);
		Globals.setSubTitleFont(Globals.dbSubtitleFont);
		Globals.setSubTitleFile(Globals.dbSubtitleFile);
		Globals.setSubTitlePos(Globals.dbSubtitlePos);
		Globals.setSubTitleCol(Globals.dbSubtitleCol);
		//DemoRenderer.UpdateValuesFromSettings();
	}
	private class DownloadTask extends AsyncTask<String, Integer, Integer>{
		ProgressDialog mProgressDialog  ;

		@Override
		protected Integer doInBackground(String... params) {
			// TODO Auto-generated method stub
			
			String temp = Globals.fileName.substring(Globals.fileName.lastIndexOf("/")+1,Globals.fileName.length()-4);
			temp = "/" + temp +  ".srt";
			if(!subtemp.equals(temp)){
				subtemp = Globals.fileName.substring(Globals.fileName.lastIndexOf("/")+1,Globals.fileName.length()-4);
				subtemp = "/" + subtemp + ".srt";
				try {
					URL url = new URL(params[0]);
					URLConnection connection = url.openConnection();
					connection.connect();
		            // this will be useful so that you can show a typical 0-100% progress bar
		            int fileLength = connection.getContentLength();
					InputStream input = new BufferedInputStream(url.openStream());
					OutputStream output = new FileOutputStream(Globals.getSdcardPath()+subtemp );
					byte data[] = new byte[1024];
		            int count;
		            long total = 0;
		            while ((count = input.read(data)) != -1) {
		                output.write(data, 0, count);
		                total += count;
		                publishProgress((int) (total * 100 / fileLength));
		            }
		            output.flush();
		            output.close();
		            input.close();
					
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return null;
		}
		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO  Auto-generated   method    stub
			super.onProgressUpdate(values);
			mProgressDialog.setProgress(values[0]);
		}
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated    method stub
			super.onPreExecute();
			mProgressDialog = new ProgressDialog(VideoPlayerActivity.this);
			mProgressDialog.setMessage("Download Subtitle");
			mProgressDialog.setIndeterminate(false);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgressDialog.show();
		}
		@Override
		protected void onPostExecute(Integer result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			//String temp = 	    Globals.dbSubtitleFile;
			//Globals.setSubTitleFile("/mnt/sdcard/subtemp.srt");
			mProgressDialog.dismiss();
			//demoRenderer.nativePlayerSetAspectRatio(Globals.getSdcardPath()+subtemp,1);
			mSubtitle.LoadSubtitle(Globals.getSdcardPath()+subtemp);
			if(mSubtitle.isParseSubtitle()){
				mOverPlay.showInfo("Loaded Subtitle: " + Globals.getSdcardPath()+subtemp, 3000);
			}
			//toast("Downloaded Subtitle:"+Globals.getSdcardPath()+subtemp);
		}
		
	}
	public void restartUpdater() {
		seekBarUpdater.stopIt();
		seekBarUpdater = new Updater();
		mHandler.postDelayed(seekBarUpdater, 100);
	}
	OnClickListener mcPlayListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if(paused) {
				mediaPlayer.start();
				seekBarUpdater = new Updater();
				mHandler.postDelayed(seekBarUpdater, 10);
				mcPlay.setImageResource(R.drawable.mediacontroller_pause01);
			}else {
				mediaPlayer.pause();
				seekBarUpdater.stopIt();						
				mcPlay.setImageResource(R.drawable.mediacontroller_play01);
			}		        	
			paused = !paused;
		}
	};
	OnSeekBarChangeListener mcSeekChangeListener = new OnSeekBarChangeListener() {
		
		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
			log("stop SeekBar");
			int progress = seekBar.getProgress();
			mediaPlayer.seekTo(progress*totalDuration);
			bSeeking = false;
			if (!paused) {
				restartUpdater();
			} 
			mOverPlay.hideInfo();
		}
		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
			log("start SeekBar");
			bSeeking = true;
		}
		
		@Override
		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
			if(fromUser) {
				int currentSecsMoved = (int)((totalDuration * ((float) (progress / 10F ))) / 100);
				String timeMoved = Utils.formatTime(currentSecsMoved);
				//scrolledtime.setText(timeMoved);
				mcCurrentTime.setText(timeMoved);
				//resetAutoHider();
				mOverPlay.showInfo(timeMoved);
			}
		}
	};
	OnClickListener mMainViewListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if(mcLayout.getVisibility() == View.VISIBLE){
				mcLayout.setVisibility(View.GONE);
			}else{
				mcLayout.setVisibility(View.VISIBLE);
			}
		}
	};
	public void surfaceCreated(SurfaceHolder holder) {
		Log.v(LOGTAG, " surfaceCreated Called");
		
		mediaPlayer.setDisplay(holder);
		
		try {
			mediaPlayer.prepareAsync();
		} catch (IllegalStateException e) {
			Log.v(LOGTAG, "IllegalStateException " + e.getMessage());
			finish();
		}

	}

	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		Log.v(LOGTAG, "surfaceChanged Called");
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		Log.v(LOGTAG, "surfaceDestroyed Called");
	}

	public void onCompletion(MediaPlayer mp) {
		Log.v(LOGTAG, "onCompletion Called");
	}

	public boolean onError(MediaPlayer mp, int whatError, int extra) {
		Log.v(LOGTAG, "onError Called");
		if (whatError == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
			Log.v(LOGTAG, "Media Error, Server Died " + extra);
		} else if (whatError == MediaPlayer.MEDIA_ERROR_UNKNOWN) {
			Log.v(LOGTAG, "Media Error, Error Unknown " + extra);
		}
		return false;
	}

	public boolean onInfo(MediaPlayer mp, int whatInfo, int extra) {
		if (whatInfo == MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING) {
			Log.v(LOGTAG, "Media Info, Media Info Bad Interleaving " + extra);
		} else if (whatInfo == MediaPlayer.MEDIA_INFO_NOT_SEEKABLE) {
			Log.v(LOGTAG, "Media Info, Media Info Not Seekable " + extra);
		} else if (whatInfo == MediaPlayer.MEDIA_INFO_UNKNOWN) {
			Log.v(LOGTAG, "Media Info, Media Info Unknown " + extra);
		} else if (whatInfo == MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING) {
			Log.v(LOGTAG, "MediaInfo, Media Info Video Track Lagging " + extra);
		} 
		return false;
	}
	
	public void onPrepared(MediaPlayer mp) {
		Log.v(LOGTAG, "onPrepared Called");
		mp.start();
		mVideoWidth = mp.getVideoWidth();
		mVideoHeight = mp.getVideoHeight();
		mp.seekTo(postionBeforeSetting);
		mcFileName.setText(mTitle);
		mcTotalTime.setText(Utils.formatTime(mp.getDuration()/1000));
		seekBarUpdater = new Updater();
		mHandler.postDelayed(seekBarUpdater, 100);
		
		
	}
	private class Updater implements Runnable {
		private boolean stop;

		public void stopIt() {
			System.out.println("Stopped updater");
			stop = true;
		}
		@Override
		public void run() {
			if(!bSeeking){
				playedDuration = mediaPlayer.getCurrentPosition()/1000;
				mcCurrentTime.setText(Utils.formatTime(mediaPlayer.getCurrentPosition()/1000));
				
				if(!stop) {
					mHandler.postDelayed(seekBarUpdater, 100);
					totalDuration = mediaPlayer.getDuration()/1000;
					if(totalDuration != 0) {
						int progress = (int)((1000 * playedDuration) / totalDuration);
						mcSeek.setProgress(progress);							
						mcTotalTime.setText(Utils.formatTime(totalDuration));
						mSubtitle.findSubTitle(1000*playedDuration);
						
						log(String.valueOf(TrafficStats.getUidRxBytes(getApplication().getApplicationInfo().uid)));
					}	
				}
			}
		}
	}
	public void onSeekComplete(MediaPlayer mp) {
		Log.v(LOGTAG, "onSeekComplete Called");

	}

	public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
		Log.v(LOGTAG, "onVideoSizeChanged Called");
	}

	public void onBufferingUpdate(MediaPlayer mp, int bufferedPercent) {
		Log.v(LOGTAG, "MediaPlayer Buffering: " + bufferedPercent + "%");
	}

	public boolean canPause() {
		return true;
	}

	public boolean canSeekBackward() {
		return true;
	}

	public boolean canSeekForward() {
		return true;
	}

	public int getBufferPercentage() {
		return 0;
	}

	public int getCurrentPosition() {
		return mediaPlayer.getCurrentPosition();
	}

	public int getDuration() {
		return mediaPlayer.getDuration();
	}

	public boolean isPlaying() {
		return mediaPlayer.isPlaying();
	}

	public void pause() {
		if (mediaPlayer.isPlaying()) {
			mediaPlayer.pause();
		}
	}

	public void seekTo(int pos) {
		mediaPlayer.seekTo(pos);
	}

	public void start() {
		mediaPlayer.start();
	}

}
